import React, { PureComponent } from 'react';
import {
  Form, Input, Select, Button, Card, Icon, Upload, message, Modal } from 'antd';
import { connect } from 'dva';
import globalConstant from '../../utils/globalConstant';

const FormItem = Form.Item;

// TODO 缺少图片判断   需要判断图片2张

@connect(({ masterManage, general, loading }) => ({
  masterManage,
  general,
  loading: loading.models.masterManage,
}))
@Form.create()
export default class ShowMasterInfo extends PureComponent {
  state ={
    uploadFileLength: [],
    previewVisible: false,
    previewImage: '',
    newFileFlag: false,
    fileList:[],
  }
  componentDidMount() {
    this.props.dispatch({
      type: 'masterManage/getMasterInfo',
      payload: {
        id: this.props.masterId,
      },
      callback:() =>{
        const fileList = [];
        const { masterManage: { masterInfo } } = this.props;
        fileList.push({
          uid: -1,
          status: 'done',
          url: masterInfo.idcardPhotoFront,
        });
        fileList.push({
          uid: -2,
          status: 'done',
          url: masterInfo.idcardPhotoSide,
        });
        this.setState({
          fileList: fileList,
        }); 
      }

    });
    this.props.dispatch({
      type: 'general/getDistrictList',
    });
    
  }
  handleSubmit = (e) => {
    /*
      禁用默认事件
     */
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      console.log(values.upload)
      console.log(this.state.fileList)
      if(values.upload.length!==2){
        message.success(`请上传身份证照片正反面`);
        return;
      }
      if (!err) {
        console.log('subValue', values);
        this.props.form.resetFields();
        const fileListArr = [];
        for(var item in values.upload){
          if(values.upload[item].response !==undefined){
            values.upload[item].response.data.map(items => fileListArr.push(items.fileUrl))
          }else{
            fileListArr.push(values.upload[item].url)
          }
        }
        console.log('fileListLength', fileListArr.toString());
        const serviceArray = [];
        values.serviceAddres.map((item) => {
          return serviceArray.push({ districtId: item });
        });
        console.log('serviceArray', serviceArray);
        console.log('fileListArr', fileListArr);
        this.props.dispatch({
          type: 'masterManage/updateMaster',
          payload: {
            id: this.props.masterId,
            idcardPhotoFront: fileListArr[0] || null,
            idcardPhotoSide: fileListArr[1] || null,
            loginName: values.name,
            loginPassword: values.userPwd,
            userName: values.userName,
            userMobile: values.phoneNumber,
            userIdcard: values.Identity,
            serviceAddrs: serviceArray,
          },
          callback: () => {
            /*
              子组件向父组件传参数
             */
            this.props.handCancel();
          },
        });
      }
    });
  }
  normFile = (e) => {
    console.log('Upload event:', e);
    if (Array.isArray(e)) {
      return e;
    }
    this.setState({
      uploadFileLength: e.fileList,
      newFileFlag: true,
    });
    return e && e.fileList;
  }
  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }
  handleCancel=() => {
    this.setState({
      previewVisible: false,
    });
  }
  render() {
    const { masterManage: { masterInfo }, general: { districtList } } = this.props;
    console.log('masterInfo', masterInfo);
    const { uploadFileLength, previewImage, previewVisible,fileList } = this.state;
    const { getFieldDecorator, getFieldValue } = this.props.form;
    
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };
    const children = [];
    console.log('districtList', districtList);
    districtList.map((item, index) => (
      children.push(
        <Select.Option
          key={index.toString()}
          value={item.id}
        >{item.districtName}
        </Select.Option>)
    ));
    const updateProps = {
      name: 'file',
      action: globalConstant.fileUploadURL,
      headers: {
        authorization: 'authorization-text',
      },
      listType: 'picture-card',
      onChange:(info)=> {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status == 'removed') {
          this.setState({
            fileList: info.fileList,
          });
          console.log('文件删除',info.file, info.fileList);
          console.log('文件删除aaa',info.file, this.state.fileList);
        }
        if (info.file.status === 'done') {
          this.setState({
            fileList: info.fileList,
          });
          console.log('doneInfo',info);
          message.success(`${info.file.name} 文件上传成功`);
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} file upload failed.`);
        }
      },
    };
    const serviceAddressArray = [];
    masterInfo.serviceAddres && masterInfo.serviceAddres.map(item => serviceAddressArray.push(item.districtId));
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div >点击选择</div>
      </div>
    );
    return (
      <Card bordered={false} loading={this.props.loading}>
        <Form
          onSubmit={this.handleSubmit}
          style={{ marginTop: 8 }}
        >
          <FormItem
            {...formItemLayout}
            label="登录账号"
          >
            {getFieldDecorator('userName', {
              rules: [{
                required: true, message: '请输入登录账号',
              }],
              initialValue: masterInfo.loginName,
            })(
              <Input placeholder="请输入登录账号" />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="师傅名字"
          >
            {getFieldDecorator('name', {
              rules: [{
                required: true, message: '请输入姓名',
              }],
              initialValue: masterInfo.userName,
            })(
              <Input placeholder="请输入姓名" />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="联系电话"
          >
            {getFieldDecorator('phoneNumber', {
              rules: [{
                required: true, message: '请输入联系电话',
              }],
              initialValue: masterInfo.userMobile,
            })(
              <Input placeholder="请输入联系电话" />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="电子邮箱"
          >
            {getFieldDecorator('email', {
              initialValue: masterInfo.userEmail,
            })(
              <Input placeholder="请输入电子邮箱" />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="身份证号"
          >
            {getFieldDecorator('Identity', {
              rules: [{
                required: true, message: '请输入身份证号',
              }],
              initialValue: masterInfo.userIdcard,
            })(
              <Input placeholder="请输入身份证号" />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="服务区域"
          >
            {getFieldDecorator('serviceAddres', {
              rules: [{
                type: 'array',
              }],
              initialValue: serviceAddressArray,
            })(
              <Select
                mode="multiple"
                style={{ width: '100%' }}
                placeholder="请选择服务区域"
              >
                {children}
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="上传身份证"
          >
            {getFieldDecorator('upload', {
              rules: [{
                required: true, message: '请上传身份证',
              }],
              valuePropName: 'fileList',
              getValueFromEvent: this.normFile,
              initialValue: fileList,
            })(
              <Upload {...updateProps} onPreview={this.handlePreview}>
                {fileList.length >= 2 ? null : uploadButton}
              </Upload>
            )}
          </FormItem>
          <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </FormItem>
        </Form>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </Card>
    );
  }
}
